package com.scmp.provider.bap.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * RestTemplate用于同步client端的核心类，简化了与http服务的通信，并满足RestFul原则，程序代码可以给它提供URL，并提取结果
 * 默认情况下，RestTemplate默认使用jdk提供http链接的能力（HttpURLConnection）
 * 可以通过setRequestFactory属性切换到不同的HTTP源，Apache HttpComponents,Netty和OkHttp。
 */
@Configuration
public class RestTemplateConfig {

//    Logger log = LoggerFactory.getLogger(RestTemplateConfig.class);

    /**
        HttpMessageConverter对象转换器
        ClientHttpRequestFactory  默认是jdk的HttpURLConnection
        ResponseErrorHandler 异常处理
        ClientHttpRequestInterceptor 请求拦截器
     */
    @Bean
    public RestTemplate restTemplate( RestTemplateBuilder builder,HttpClient httpClient){
        RestTemplate restTemplate = builder
                .errorHandler(new CustomResponseErrorHandler())
                .basicAuthentication("ycj","123")
                .interceptors(new HeadClientHttpRequestInterceptor())//可以添加多个，可以是多参，也可以集合
                .build();
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.getMessageConverters().add(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        System.out.println(messageConverters);
        return restTemplate;
    }

    @Bean
    @ConditionalOnMissingBean(HttpClient.class)//该注解表示，如果存在它修饰的类的bean,则不需要创建这个bean
    public HttpClient httpClient(){
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(1000000)
                .build();
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setUserAgent("agent")
                .setMaxConnPerRoute(10)
                .setMaxConnTotal(50)
                .build();
    }

}
